// pages/addSchedule/index.js
import { changeParticipantInfo } from '../../api/information.js'
import REG from "../../utils/reg";
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userFormList:[
      { name: '姓名 Name', type: 'text', request: 1, mode:'', check: 'text', value: '', placeholder:'请填写真实姓名',errTitle:''},
      { name: '性别 Gender', type: 'button', request: 1, mode: '', value: 0, select: ['男 Man', '女 Lady'],placeholder:'请填写真实姓名',errTitle:''},
      { name: '手机号码 Cellphone', type: 'Number', request: 1, mode: '', check: 'phone', value: '', placeholder:'请填写手机号码',errTitle:''},
      { name: '证件类型 Type of certificate', type: 'picker', request: 1, mode: 'select', select: ['请选择证件类型', '身份证','护照','港澳居民来往内陆通行证','台胞证'], value: 0, placeholder:'请选择证件类型',errTitle:''},
      { name: '证件号码 ID', type: 'Number', request: 1, mode: '', check: 'card', value: '', placeholder:'请根据证件类型填写正确证件号码',errTitle:''},
      
      { name: '出生日期 Birthdate', type: 'picker', request: 1, mode: 'date', value: '', placeholder:'请选择出生日期',errTitle:''},
      { name: '血型 Blood type', type: 'picker', request: 1, mode: 'select', select: ['请选择血型', 'A', 'B', 'AB', 'O', 'Rh', '不详'], value: 0,placeholder: '请选择血型',errTitle:''},
      { name: '服装尺码 T-shirt size', type: 'picker', request: 1, mode: 'select', select: ['请填写服装尺码', 'XS', 'S', 'M', 'L', 'XL', 'XXL', 'XXXL'], placeholder: '请填写服装尺码',value:0,errTitle:''},
      { name: '紧急联系人 Emergency contact', type: 'text', request: 1, mode: '', value: '', placeholder:'请填写紧急联系人姓名',errTitle:''},
      { name: '紧急联系人手机号码 Emergency contact phone', type: 'Number', request: 1, mode: '',check: 'phone', value: '', placeholder:'请填写紧急联系人手机号码',errTitle:''},
      {name: '所在地区 Region', type: 'picker', mode:'multiSelector', request: 1, check: 'picker', value: '', placeholder:'请选择所在地区',errTitle:''},
      { name: '详细地址 Address', type: 'text', request: 1, mode: '', check: 'text', value: '', placeholder:'请填写所在地区详细地址',errTitle:''},
      { name: '邮箱 E-mail', type: 'text', request: 1, mode: '', check: 'email', value: '', placeholder: '请填写电子邮箱', errTitle: '' }
    ],
    time: {
      start: 365*90+25, // 开始时间是今天的前90年
      end: 0 // 结束时间是今天的0天后
    },
    start: '1930-4-15',
    end: '2020-4-17',
    isRequst: false,//用来判断当前是否为请求状态
    multiIndex: [0, 0, 0],
    multiArray: []
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.text) {
      wx.setNavigationBarTitle({
        title: options.text
      })
    }
    let { start, end } = this.data.time
    let day1 = new Date().valueOf();
    let startTime = new Date(day1 - (24 * 60 * 60 * 1000 * start));
    let endTime = new Date(day1 + (24 * 60 * 60 * 1000 * end));
    let start1 = startTime.getFullYear() + '-' + (startTime.getMonth() + 1) + '-' + startTime.getDate();
    let end1 = endTime.getFullYear() + '-' + (endTime.getMonth() + 1) + '-' + endTime.getDate();
    this.setData({ start: start1, end: end1})
  },
  onShow() {
    app._getAddressInfo(data => {
      this.setData({multiArray: data[0] })
      this.bindMultiPickerColumnChange({ detail: { column: 0, value: 0 } })
    })
  },
   // 输入框赋值
  getInputValue(e){
    this.setData({ [`userFormList[${e.currentTarget.dataset.index}].value`]: e.detail.value})
    let { check, value } = this.data.userFormList[e.currentTarget.dataset.index]
    let errTitle = ''
    switch (check) {
      case 'phone':
        errTitle = REG.isPoneAvailable(value) ? '' : '请填写正确的手机号码'
        break;
      case 'email':
        errTitle = REG.isEmail(value) ? '' : '请填写正确的邮箱'
        break;
      case 'card':
        if (this.data.userFormList[3].value == 1) {
          errTitle = REG.isIdCard(value) ? '' : '请填写正确的身份证号码'
        }
        break;
      default:
        break;
    }
    this.setData({ [`userFormList[${e.currentTarget.dataset.index}].errTitle`]: (errTitle != '' ? errTitle : '') })
  },
   // 性别切换
  bindBtn(e) {
    this.setData({ [`userFormList[${e.currentTarget.dataset.parindex}].value`]: e.currentTarget.dataset.index })
  },
  //Picker选择（非地区选择）
  bindPickerChange: function (e) {
    this.setData({ [`userFormList[${e.currentTarget.dataset.index}].value`]: e.detail.value })
    let { type, mode, placeholder, value } = this.data.userFormList[e.currentTarget.dataset.index]
    console.log(e)
    if (type == 'picker' && (mode == 'select' || mode == 'date')) {
      this.setData({ [`userFormList[${e.currentTarget.dataset.index}].errTitle`]: (value == 0 ? placeholder : '') })
    }
  },
   //Picker地区选择
  bindMultiPickerColumnChange(e) {
    let multiIndex = this.data.multiIndex
    multiIndex[e.detail.column] = e.detail.value
    this.setData({ ...app._processingAreaData(multiIndex) })
  },
  //检查填写项
  checkValue(callback) {
    let { userFormList } = this.data
    let state = true
    userFormList.forEach((e, i) => {
      if (e.request == 1 && e.mode != 'multiSelector') { // 没有报错项必填项和非地区picker
        if (e.type == 'text' || e.type == 'Number') {
          if (e.value == '') {
            e.errTitle = e.placeholder
          } else {
            switch (e.check) {
              case 'phone':
                e.errTitle = REG.isPoneAvailable(e.value) ? '' : '请填写正确的手机号码'
                break;
              case 'card':
                if (userFormList[3].value == 1) {
                  e.errTitle = REG.isIdCard(e.value) ? '' : '请填写正确的身份证号码'
                }
                break;
              case 'email':
                e.errTitle = REG.isEmail(e.value) ? '' : '请填写正确的邮箱'
                break;
            }
          }
        } else if (e.type == 'picker') {
          if (e.mode == 'select') { // 单选择器
            if (e.value <= 0) {
              e.errTitle = e.placeholder
            }
          } else if (e.mode == 'date') { // 日期选择器
            if (e.value == '') {
              e.errTitle = e.placeholder
            }
          }
        }
        if (e.errTitle != '' && state) {
          state = false
        }
      }
      if (i == userFormList.length - 1) {
        this.setData({ userFormList: userFormList })
        if (!state) {
          wx.showToast({ title: '请检查填写项', icon: 'none' })
        }
        callback(state)
      }
    })
  },
  submit(){
    if (!this.data.isRequst){
      let { userFormList, multiArray, multiIndex } = this.data
      this.checkValue(state=>{
        if (state) {
          this.setData({ isRequst: true })
            let address = '';
            if (multiArray[0][multiIndex[0]]) {
              address += multiArray[0][multiIndex[0]]
            }
            if (multiArray[1][multiIndex[1]]) {
              address += (',' + multiArray[1][multiIndex[1]])
            }
            if (multiArray[2][multiIndex[2]]) {
              address += (',' + multiArray[2][multiIndex[2]])
            }
          let obj = {
            name: userFormList[0].value,
            sex: Number(userFormList[1].value)+1,
            phone: userFormList[2].value,
            certificateType: userFormList[3].select[userFormList[3].value],
            identity: userFormList[4].value,
            birthday: userFormList[5].value,
            bloodType: userFormList[6].select[userFormList[6].value],
            size: userFormList[7].select[userFormList[7].value],
            linkMan: userFormList[8].value,
            linkPhone: userFormList[9].value,
            shortAddress: address,
            address: userFormList[11].value,
            email: userFormList[12].value
          }
          changeParticipantInfo(obj).then(res=>{
            if (res.code == 0) {
              wx.showToast({title: '添加成功',duration: 2000})
              setTimeout(function() {
                wx.navigateBack(1)
              }, 2000);
            }else{
              wx.showToast({
                title: res.msg,
                icon: 'none',
                duration: 2000
              })
            }
          })
          this.setData({ isRequst: false })
        }
      })
     
    }
  }
})